﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Trul.Framework.Security;
using Trul.WebUI.Helper;

namespace Trul.WebUI.Infrastructure
{
    public sealed class LogonAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext) {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            if(!skipAuthorization) {
                base.OnAuthorization(filterContext);
            }
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
            if(!filterContext.HttpContext.User.Identity.IsAuthenticated) {
                base.HandleUnauthorizedRequest(filterContext);
            } else if(!(filterContext.HttpContext.User as ICustomPrincipal).IsInRole(Roles)) {
                throw new HttpException(403, ResourceHelper.GetGlobalResource("AccessDenied"));
            }
        }
    }
}